package com.han.methodlog.aspect;

import com.han.methodlog.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;

@Aspect
@Component
@Slf4j
public class MethodLogAspect {

    @Resource
    private MailService mailService;


    @Around("@annotation(com.han.methodlog.annotation.MethodLog)")
    public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getMethod().getName();
        Object[] args = joinPoint.getArgs();
        log.info("{} 开始执行 , 入参{}", methodName, Arrays.toString(args));
        Object result = null;
        boolean success = true;
        long duration = 0;
        try {
            Long methodStartTime = System.currentTimeMillis();
            result = joinPoint.proceed();
            Long methodEndTime = System.currentTimeMillis();
            duration = methodEndTime - methodStartTime;
        } catch (Exception e) {
            success = false;
            // 发送报错信息
            String subject = methodName + "发生了异常";
            // todo 这里可以写一个html模板
            String message = "报错信息->"+ e.getMessage();
            mailService.sendMail(subject, message);
            throw e;
        } finally {
            log.info("{} 执行完成，出参:{} ,执行时间:{}, 是否成功:{}", methodName, duration, result, success);
        }

        return result;
    }

}
